package com.zxmr.utility.action;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.zxmr.action.Request;
import com.zxmr.action.Response;
import com.zxmr.action.ResponsePayload;
import com.zxmr.action.ResultCode;
import com.zxmr.domain.Notification;
import com.zxmr.domain.service.NotificationService;
import com.zxmr.navigate.ExecuteException;
import com.zxmr.navigate.Executor;

public class NotificationAction extends Executor{

	enum method{
		add,
		query,
		queryUnRead,
		awared;
	}
	@Override
	public void execute(Request request, Response response) {

		try
		{
			method m = Enum.valueOf(method.class, this.getElement().getMethod());
			switch(m)
			{
			case add:
				add(request,response);
				break;
			case query:
				break;
			case queryUnRead:
				queryUnRead(request,response);
				break;
			case awared:
				awared(request,response);
				break;
			}

		}catch(Exception e)
		{
			ResponsePayload payload = new ResponsePayload();
			if(e instanceof ExecuteException)
			{
				payload.setValue(e.getMessage());
			}else
			{
				e.printStackTrace();
				payload.setValue("internal error");
			}
			response.setPayload(payload);
			response.setResult(ResultCode.COMPONENT_ERROR);
		}
		
	}
	
	private void add(Request request,Response response)throws ExecuteException
	{
		Notification notification = parseRequest(request);
		NotificationService service = new NotificationService();
		service.add(notification);
	}

	private Notification parseRequest(Request request)throws ExecuteException
	{
		try
		{
			return JSON.parseObject(request.getRequestParameters().get("p"), Notification.class);
		}catch(Exception e)
		{
			throw new ExecuteException("invalid parameter");
		}
	}
	private void queryUnRead(Request request,Response response)throws ExecuteException
	{
		NotificationService service = new NotificationService();
		List<Notification> notifications = service.queryAllUnRead(request.getAccount().getName());
		
		ResponsePayload payload = new ResponsePayload(JSON.toJSONString(notifications));
		response.setPayload(payload);
	}
	private void awared(Request request,Response response)throws ExecuteException
	{
		long id = 0;
		try
		{
			id = Long.parseLong(request.getRequestParameters().get("id"));
		}catch(Exception e)
		{
			throw new ExecuteException("invalid parameter");
		}
		NotificationService service = new NotificationService();
		Notification noti = service.query(id, request.getAccount().getName());
		if(noti == null)
		{
			throw new ExecuteException("no such notification");
		}
		
		service.setAsReaded(noti);
	}
}
